package nl.mayisal.metadata.factories;

import java.util.Collection;

import nl.mayisal.metadata.DatabaseStructure;
import nl.mayisal.metadata.TableRelation;
import nl.mayisal.metadata.TableStructure;
import nl.mayisal.metadata.columns.AbstractColumnStructure;
import nl.mayisal.sql.SQLConnection;

public class DatabaseStructureFactory {
	private static final String TABLE_TYPE = "TABLE";

	public static DatabaseStructure createStructure(SQLConnection connection) {
		DatabaseStructure database = new DatabaseStructure(connection.getCatalogName());
		Collection<String> tableTypes = connection.getAvailableTableTypes();
		if (tableTypes.contains(DatabaseStructureFactory.TABLE_TYPE)) {
			Collection<String> tableNames = connection.getTableNames(DatabaseStructureFactory.TABLE_TYPE);
			for (String tableName : tableNames) {
				TableStructure table = new TableStructure(tableName);
				Collection<AbstractColumnStructure<?>> columns = connection.getColumns(tableName);
				for (AbstractColumnStructure<?> column : columns) {
					table.addColumn(column.getName(),column);
				}
				database.addTable(table.getName(),table);
			}
			for (TableStructure table : database.getTables().values()) {			
				for (TableRelation relation : connection.getRelations(database,table)) {					
					table.addRelation(relation.getParentColumn().getName(), relation);				
				};
			}

		}
		return database;
	}

}
